package ua.edu.nuos.jeetraining2012.cms.servlet;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ua.edu.nuos.jeetraining2012.cms.entity.UserEntity;
import ua.edu.nuos.jeetraining2012.cms.service.Course;
import ua.edu.nuos.jeetraining2012.cms.util.interceptor.ShiroSecurity;
import ua.edu.nuos.jeetraining2012.cms.util.servlet.CmsServlet;

import javax.ejb.EJB;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ShiroSecurity
@WebServlet(urlPatterns = "")
public class DefaultServlet extends CmsServlet {

    /** Define course logic. */
    @EJB
    private Course course;

    /** Define logger. */
    final static private Logger logger = LoggerFactory.getLogger(DefaultServlet.class);

    public void indexAction(HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.debug("indexAction() - started.");

        final Subject subject = SecurityUtils.getSubject();

        if (subject != null && subject.isAuthenticated()) {
            UserEntity user = (UserEntity) subject.getSession().getAttribute("user");
            if (user != null) {
                if (course.countMyCourses(user.getId()) > 0) {
                    logger.debug("User has more than 0 courses in subscription list. Redirecting to his courses.");
                    response.sendRedirect(request.getContextPath() + "/course/mycourses");
                    return;
                }
            }
        }
        logger.debug("User has no any courses in his subscription list yet. Redirecting to course list.");
        response.sendRedirect(request.getContextPath() + "/course");
        return;
    }
}
